<?php

namespace app\model\v1\gift;


use app\model\user\User;
use crmeb\traits\ModelTrait;
use think\Exception;
use think\facade\Db;
use think\Model;


class GiftCardNumber extends Model
{

    use ModelTrait;

    protected $updateTime = false;
    protected $createTime = false;

    protected $hidden = [
    //    'create_time','update_time','delete_time'
    ];

    protected $table = 'eb_gift_card_number';



    public function user()
    {
        return $this->hasOne(User::class, 'uid', 'use_uid');
    }

    public function recuser()
    {
        return $this->hasOne(User::class, 'uid', 'act_uid');
    }



    public function batch()
    {
        return $this->hasOne(GiftCardBatch::class, 'id', 'card_batch_id');
    }




    /**
     * 实体卡管理列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getCardNumberList($params = [])
    {
        $data["data"] = self::alias("a")
            ->field("a.*,FROM_UNIXTIME(a.create_time) as create_time,FROM_UNIXTIME(a.buy_time) as buy_time,FROM_UNIXTIME(a.act_time) as act_time,
             case when a.status=1 then '激活' 
                when a.status=2 then '未激活' 
                end as status_text
            ")
            ->with([
                'user'=> function($query) {
                    $query->field('uid,nickname,real_name,phone');
                },
                'batch'=> function($query) {
                    $query->field('title,id,total_num');
                },
                'recuser'=> function($query) {
                    $query->field('uid,nickname,real_name,phone');
                },
            ])
            ->whereNull("a.delete_time")
            ->join('user b','a.use_uid=b.uid','left')
            ->where(function ($query) use ($params){
                if(!empty($params['time'])){
                    $wheretime = explode (',',$params['time']);
                    $query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($params["word"])) $query->where("a.card_number",'like', '%'.$params["word"].'%');
                if(!empty($params["phone"])) $query->where("b.phone",'like', '%'.$params["phone"].'%');
                if(!empty($params["status"])) $query->where("a.status", $params["status"]);
            })
            ->order(['id'=>'asc'])
            ->page($params["page"], $params['limit'])
            ->select()->toArray();

        $data["count"] = self::alias("a")
            ->field("a.*,FROM_UNIXTIME(a.create_time) as create_time")
            ->with([
                'user'=> function($query) {
                    $query->field('uid,nickname,real_name,phone');
                },
                'batch'=> function($query) {
                    $query->field('title,id,total_num');
                },
            ])
            ->whereNull("a.delete_time")
            ->join('user b','a.use_uid=b.uid','left')
            ->where(function ($query) use ($params){
                if(!empty($params['time'])){
                    $wheretime = explode (',',$params['time']);
                    $query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($params["word"])) $query->where("a.card_number",'like', '%'.$params["word"].'%');
                if(!empty($params["phone"])) $query->where("b.phone",'like', '%'.$params["phone"].'%');
                if(!empty($params["status"])) $query->where("a.status", $params["status"]);
            })
            ->count();

        return $data;
    }




    /**
     * 实体卡管理列表 - 启用禁用
     * @param $param
     * @return string
     */
    public static function enableCardNumber($param = [])
    {
        //获取用户发送的id，根据状态修改当前banner的启用禁用状态
        $status = self::where("id", $param['id'])->value("status");
        $msg = '';
        if($status == 1){   //1启用 2禁用
            $enable = 2;
            $msg = "禁用成功";
        }else{
            $enable = 1;
            $msg = "启用成功";
        }
        self::where("id", $param['id'])->update(['status' => $enable]);
        return $msg;
    }



    public static function createOne($card_batch_id='', $card_number='', $card_password='', $use_uid='',$status=2)
    {
        try {
            ////Db::startTrans();

            $add = [
                "card_batch_id" => $card_batch_id,
                "card_number"   => $card_number,
                "card_password" => $card_password,
               // "use_uid"       => $use_uid,
                "status"        => $status,
                "use_time"      => time(),
                "create_time"   => time(),
            ];
            $res = self::insert($add);

            ////$res = Db::name('gift_card_batch')->where('id', $card_batch_id)->inc('use_num', 1)->update();

            ////Db::commit();

            return $res;
        }catch (\Throwable $e){
            Db::rollback();
            Throw new Exception($e->getMessage());
        }

    }



    public static function createAll($add_number = [])
    {
        return self::saveAll($add_number);
    }



    public static function setUseUid($num='', $uid='', $gift_card_id='')
    {
        try {
            Db::startTrans();

            $ids = self::whereNull("use_uid")->order("id", "asc")->limit($num)->column("id") ?? [];
            $find = self::whereNull("use_uid")->order("id", "asc")->limit(1)->find() ?? [];
            if(!empty($find)){
                ////if( ($find['total_num'] - $find['use_num']) < $num){
                    //本批次实体卡数量不足
                    //Throw new Exception("本批次实体卡数量不足.");

                    $available_batch_id = self::getAvailableBatchIds($find['card_batch_id'], $num);
                    if(empty($available_batch_id)) Throw new Exception("本批次实体卡数量不足.");

                    $ids = self::whereNull("use_uid")->where("card_batch_id", $available_batch_id)->order("id", "asc")->limit($num)->column("id") ?? [];
                    $res = self::whereIn("id", $ids)->update(["use_uid" => $uid, "buy_time" => time(), "gift_card_id"=>$gift_card_id]);
                    GiftCardBatch::where("id", $find['card_batch_id'])->inc('use_num', $num)->update();
                ////}else{
                    ////$res = self::whereIn("id", $ids)->update(["use_uid" => $uid, "buy_time" => time(), "gift_card_id"=>$gift_card_id]);
                    ////GiftCardBatch::where("id", $find['card_batch_id'])->inc('use_num', $num)->update();
                ////}
            }else{
                Throw new Exception("暂无实体卡.");
            }


            Db::commit();
            return $ids;
        }catch (\Throwable $e){
            Db::rollback();
            Throw new Exception($e->getMessage());
        }
    }



    public static function getNumberByIds($ids = '')
    {
        return self::whereIn("id", $ids)->order("id", "asc")->select()->toArray();
    }


    /**
     * 获取可用的批次id
     * @param $card_batch_id
     * @param $num
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getAvailableBatchIds($card_batch_id = '', $num=0)
    {
        $cardBatchIds = self::whereNull("use_uid")->where("card_batch_id", ">=",  $card_batch_id)->field("card_batch_id")->group("card_batch_id")->select()->toArray();
        if(empty($cardBatchIds)) return [];

        $available_ids = [];
        foreach ($cardBatchIds as $key => $val){
            $count = self::whereNull("use_uid")->where("card_batch_id", $val["card_batch_id"])->count();
            if($count >= $num){
                $available_ids[] = $val;
            }
        }
        return $available_ids[0]["card_batch_id"];
    }


    /**
     * 实体卡管理列表 - 已发货
     * @param $param
     * @return true
     * @throws \Exception
     */
    public static function updateCardNumberState($param = [])
    {
        try {
            Db::startTrans();

            self::where("card_number", $param['card_number'])->update(["state" => 1]);

            GiftCardUser::where("number", $param['card_number'])->update(['state' => 1]);

            Db::commit();
            return true;
        }catch (\Throwable $e){
            Db::rollback();
            Throw new \Exception($e->getMessage());
        }
    }






}